import http from "./http";
import { getUserData } from './ws'
// 注册ws

class Person {
    constructor() {
        this.isConnect = false;
        this.user = { id: -1, name: "" };
        this.ws = null;
        this.loginMessage = {};

    }



    //建立连接
    connect(user) {
        // if (this.isConnect) {
        //     return;
        // }
        let ws = new WebSocket(`${http.baseurl}${this.user.id} `);
        // console.log(user);
        this.user.id = user.id;
        this.user.name = user.name;

        ws.onopen = () => {
            this.isConnect = true;
            var mydata = new Date().toISOString();
            console.log(this.user);
            let loginMessage = getUserData(this.user.id, this.user.name, null, null, null, null, mydata);
            ws.send(JSON.stringify(loginMessage));
        }


        ws.onmessage = (res) => {
                let message = JSON.parse(res.data)
                    // console.log(res);
                switch (message.messageType) {
                    case 0:
                        {
                            this.init(message.content);
                            break;
                        }
                }
            }
            // console.log(ws);
        ws.onerror = function(res) {
            console.log(res);
        }
        ws.onclose = function(res) {
                console.log(res);
            }
            // this.ws = ws
    };
    // 初始化

    init(user) {
        this.loginMessage = user;

    }
    sendMessage() {
        console.log(this.ws);
        this.ws.send = (JSON.stringify({ originUserId: 21, targetUserId: 20, chatMsg: '2', timeStamp: new Date().toISOString() }))
    }




}

const person = new Person();
export default person;